package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.util.ConstantPropertiesUtil;
import com.atguigu.yygh.user.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/user/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取微信登录参数
     * 生成微信登录扫描二维码
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public R genQrConnect(HttpSession session){
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope","snsapi_login");
            //redirect_url:微信扫码之后，跳转到本地接口地址
            //url编码
            String url = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
            String redirect_uri = URLEncoder.encode(url, "utf-8");
            System.out.println("redirect_uri = " + redirect_uri);
            map.put("redirect_uri",redirect_uri);
            //state可以不传递
            map.put("state",System.currentTimeMillis() + "");
            return R.ok().data(map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001,"数据错误！");
        }
    }

    @GetMapping("callback")
    public String callBack(String code,String state,HttpSession session){
        //1 得到授权临时票据code
//        System.out.println("code = " + code);
//        System.out.println("state = " + state);
        //2 拿着临时票据和其他值请求微信固定接口，返回两个值 openid 和 accessToken
        //HttpClient
        //拼接请求接口和参数  get提交  ?a=1&b=2
//        String url =
//                "https://api.weixin.qq.com/sns/oauth2/access_token" +
//                        "?appid="+ConstantPropertiesUtil.WX_OPEN_APP_ID
//                        +"&secret="+ConstantPropertiesUtil.WX_OPEN_APP_SECRET
//                        +"&code="+code
//                        +"&grant_type=authorization_code";
//        String result = HttpClientUtils.get(url);
        //1.得到授权临时票据code
        System.out.println("code = " + code);
        //System.out.println("state = " + state);
        //2.拿着code和微信id和密钥，请求微信固定地址，得到两个值
        //使用code和appid以及appscrect换取access_token
        //%s 占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(), ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET, code);
        //使用httpclient请求这个地址
        try {
            String accesstokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accesstokenInfo = " + accesstokenInfo);
            //从返回字符串获取两个值 openid 和 access_token
            JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //判断数据库是否存在微信的扫描人信息
            //根据openid判断
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);
            if(userInfo == null){//数据库不村子微信消息
                //3.拿着openid和access_token请求微信地址，得到扫描人信息
                StringBuffer baseUserInfoUrl = new StringBuffer()
                        .append("https://api.weixin.qq.com/sns/userinfo")
                        .append("?access_token=%s")
                        .append("&openid=%s");
                //向%s设置参数
                String userInfoUrl = String.format(baseUserInfoUrl.toString(),
                        access_token,
                        openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultInfo = " + resultInfo);
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                //解析用户信息
                //用户昵称
                String nickname = resultUserInfoJson.getString("nickname");
                //用户头像
                String headimgurl = resultUserInfoJson.getString("headimgurl");

                //获取扫描人信息添加数据库
                userInfo = new UserInfo();
                userInfo.setName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            //返回name和token字符串
            Map<String,String> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)){
                name=userInfo.getName();
            }
            if(StringUtils.isEmpty(name)){
                name=userInfo.getPhone();
            }
            map.put("name",name);
            //判断userInfo是否有手机号，如果手机号为空，返回openid
            //如果手机号不为空，返回openid空字符串
            //前端判断:如果openid不为空，绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())){
                map.put("openid",userInfo.getOpenid());
            }else{
                map.put("openid","");
            }
            //使用jwt生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token",token);
            //跳转到前端页面
            return "redirect:http://localhost:3000/weixin/callback" +
                    "?token="+map.get("token")+
                    "&openid="+map.get("openid")+
                    "&name="+URLEncoder.encode(map.get("name"),"utf-8");
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
